import React from "react";
import { Form, DatePicker, Input, Select,Button,Col,InputNumber,TreeSelect } from "antd";
import * as Utils from "../../utils_yyr/action";
const FormItem = Form.Item;
const { Search } = Input;
const {RangePicker,MonthPicker} =DatePicker;
const { TreeNode} = TreeSelect;

class BasicForm extends React.Component {
    constructor(props){
        super(props)
        this.state ={
          fieldsValue:{}
        }
    }
    componentDidMount() {
    this.props.onRef(this);
    }
    onSubmit=(type)=>{
        const p = this;
        const { form } = p.props;
        form.validateFieldsAndScroll((err, fieldsValue) => {
          if (err) {
            return;
          }
          for(var key in fieldsValue){
            //时间范围选择器
            if(key.indexOf("frame_")===0){
              if(fieldsValue[key]&&fieldsValue[key].length){
                let arr=key.split('_');
                fieldsValue[arr[1]]= Utils.getDate(fieldsValue[key][0])
                fieldsValue[arr[2]]= Utils.getDate(fieldsValue[key][1])
              }
              delete fieldsValue[key];
            }
            //单个时间选择器
            if(key.indexOf("date_")===0){
              if(fieldsValue[key]){
                let arr=key.split('_');
                fieldsValue[arr[1]]= Utils.getDate(fieldsValue[key])
              }
              delete fieldsValue[key];
            }
            if (key.indexOf('dateSec_') === 0) {
              if (fieldsValue[key]) {
                let arr = key.split('_');
                fieldsValue[arr[1]] = Utils.getDateHHMMYY_HHMMSS(fieldsValue[key]);
              }
              delete fieldsValue[key];
            }
    
            //月选择器
            if(key.indexOf("month_")===0){
              if(fieldsValue[key]){
                let arr=key.split('_');
                fieldsValue[arr[1]]= Utils.getStringByDate(fieldsValue[key],'YYYY-MM')
              }
              delete fieldsValue[key];
            }
          }
          if(!type){
            p.props.filterSubmit(fieldsValue)
          }else{
            return fieldsValue;
          }
        })
    }
    
    //获取表单的值
    getFormValues=()=>{
      return this.onSubmit(true);
    }
  
    reset = () => {
      const p = this;
      p.props.form.resetFields();
    };
    renderTreeNodes = (data, name, valueField) =>
	// console.log(data, name, valueField)
		data && data.map(item => {
			if (item.children) {
				return (
					<TreeNode title={item[name]} key={item[valueField]} value={item[valueField]} dataRef={item}>
						{this.renderTreeNodes(item.children, name, valueField)}
					</TreeNode>
				);
			}
			return <TreeNode key={item[valueField]} value={item[valueField]} title={item[name]} {...item} />;
		});

  initFormList=()=>{
    const p = this;
    const formItemList = [];
    const { getFieldDecorator } = p.props.form;
    const { formList } = p.props;
    // 页面上的表单
    if (formList && formList.length > 0) {
      formList.forEach(item => {
        const {
          label,
          field,
          tree,
          type,
          initialValue,
          valueField,
          name,
          showTime,
          col,
          onSearch,
          required,
          placeholder
        } = item;
        const rulesType = required?[{ required: true, message: `${label}必填` }]:false;
        // const initialValue = item.initialValue || undefined;
        if (type === "TIMEFRAME") {
          const timeFrame = (
            <Col span={col===undefined?6:col}>
            <FormItem label={label} key={field} >
              {getFieldDecorator(`${field}`)(
                <RangePicker
                style={{width:'100%'}}
                  showTime={showTime?true:false}
                  placeholder={['开始时间','结束时间']}
                  format={showTime?"YYYY-MM-DD HH:mm:ss":"YYYY-MM-DD"}
                />
              )}
            </FormItem>
            </Col>
          );
          formItemList.push(timeFrame);
        } else if (type === "DATE") {
          const date = (
            <Col span={col===undefined?6:col}>
            <FormItem label={label} key={field} >
              {getFieldDecorator(`${field}`)(
                <DatePicker
                style={{width:'100%'}}
                placeholder='请选择日期'
                  showTime={showTime?true:false}
                  format={showTime?"YYYY-MM-DD HH:mm:ss":"YYYY-MM-DD"}
                />
              )}
            </FormItem>
            </Col>
          );
          formItemList.push(date);
        } else if (type === "NUMBERFRAME") {
          let arr=field.split('_');
          const number = (
            <Col span={col===undefined?8:col}>
              <Col span={12}>
              <FormItem label={label} key={field} >
              {getFieldDecorator(`${arr[1]}`)(
                <InputNumber    style={{width:'100%'}}  placeholder='最高数量'/>
              )}
            </FormItem>
              </Col>
              <Col span={12}>
              <FormItem key={field} >
              {getFieldDecorator(`${arr[2]}`)(
                <InputNumber    style={{width:'100%'}}  placeholder='最低数量' max={p.props.form.getFieldValue(arr[1])?p.props.form.getFieldValue(arr[1]):Infinity}/>
              )}
            </FormItem>
              </Col>
            
            </Col>
          );
          formItemList.push(number);
        } else if (type === "MONTHDATE") {
          const month = (
            <Col span={col===undefined?6:col}>
            <FormItem label={label} key={field} >
              {getFieldDecorator(`${field}`)(
                <MonthPicker
                placeholder={`请选择${label}`}
                style={{width:'100%'}}
                  showTime={showTime?true:false}
                />
              )}
            </FormItem>
            </Col>
          );
          formItemList.push(month);
        }else if (type === "INPUT") {
          const INPUT = (
            <Col span={col===undefined?6:col}>
              <FormItem key={field} label={label}>
              {getFieldDecorator(`${field}`,{
                  initialValue, // true | false
                  rules: rulesType,
              })(
                  <Input allowClear placeholder={placeholder?placeholder:'请填写'+label} />
              )}
              </FormItem>
            </Col>
          );
          formItemList.push(INPUT);
        } else if (type === "SEARCH") {
          const SEARCH = (
            <Col span={col===undefined?6:col}>
              <FormItem key={field} label={label}>
              {getFieldDecorator(`${field}`,{
                  initialValue, // true | false
              })(
                <Search allowClear	onSearch={(value) =>onSearch(value)} enterButton placeholder={`请选择${label}`}/>
              )}
              </FormItem>
            </Col>
          );
          formItemList.push(SEARCH);
        } else if (type === "SELECT") {
          const SELECT = (
            <Col span={col===undefined?6:col}>
            <FormItem label={label} key={field}>
            {getFieldDecorator(`${field}`,{
                initialValue, // true | false
                rules: rulesType,
            })(
              <Select  placeholder={'请选择'+label}
              showSearch
              allowClear
              filterOption={(input, option) =>
                option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
              }
              >
                {Utils.getOptionList(item.list, name,valueField)}
              </Select>
              )}
            </FormItem>
            </Col>
          );
          formItemList.push(SELECT);
        } else if (item.type === 'TREESELECT') {
					const SELECT = (
						<Col span={col===undefined?6:col}>
							<FormItem label={label} key={field}>
								{getFieldDecorator(`${field}`, {
									rules: rulesType,
									initialValue
								})(<TreeSelect onChange={this.onTreeChange} placeholder={'请选择' + label} allowClear={item.allowClear} showCheckedStrategy="SHOW_PARENT" searchPlaceholder={item.list} treeCheckable={item.treeCheckable} searchPlaceholder="Please select">
									{this.renderTreeNodes(item.list, item.name, item.valueField)}
									</TreeSelect>)}
							</FormItem>
						</Col>

					);
					formItemList.push(SELECT);
				} 
      });
    }

    return formItemList;
  }


  render() {
    const p=this;
    return <Form  {... {labelCol: {xs: { span: 30 },sm: { span:p.props.labelSpan?p.props.labelSpan:6 },},wrapperCol: {xs: {span: 24},sm: {span: p.props.labelSpan?p.props.wrapperSpan:14}}}}>
    {this.initFormList()}
    <Col span={24} style={{textAlign:'right'}}>
           <Button type="primary" icon='search' onClick={()=>this.onSubmit(false)}>查询</Button>
    </Col>
    {/* <Col span={2}>
      <Button type="primary" onClick={this.reset}>清空</Button>
    </Col> */}
    </Form>;
  }
}
export default Form.create({})(BasicForm);
